package com.fbt.energy.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.*;

@RestController
@RequestMapping("/")
public class NotifyController {

    @RequestMapping("/notify")
    public String notify(String response_content, String timestamp, String sign) {
        System.out.println("timestamp: " + timestamp);
        System.out.println("response_content: " + response_content);
        System.out.println("sign: " + sign);


        // 验签
        if(!checkSign(response_content, timestamp, sign)) {
            System.out.println("sign check failed");
            return "sign check failed";
        }
        System.out.println("sign check success");

        List<Map<String, Object>> responseContent= new ArrayList<>();
        JSONArray contentArray = JSON.parseArray(response_content);
        for(int i = 0; i < contentArray.size(); ++i) {
            HashMap<String, Object> contentMap = new HashMap<>();
            JSONObject contentObject = contentArray.getJSONObject(i);
            Set<String> keySet = contentObject.keySet();
            for(String key: keySet) {
                contentMap.put(key, contentObject.getObject(key, Object.class));
            }
            responseContent.add(contentMap);
        }

        System.out.println("接收异步通知数据：" + responseContent);

        //-----------加入业务逻辑-----------
        //--------------------------------

        return "SUCCESS";
    }

    private boolean checkSign(String response_content, String timestamp, String sign) {
        // 随机字符串 后台获取
        String nonce = "0ToUQZogw5REP7CRS7ArB";
        String buf = response_content + timestamp + nonce;
        String encode = getMD5(buf);
        return encode.equals(sign);
    }

    // md5加密
    private String getMD5(String password) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        byte[] byteArray = password.getBytes(StandardCharsets.UTF_8);

        byte[] md5Bytes = md5.digest(byteArray);
        StringBuilder hexValue = new StringBuilder();
        for (byte md5Byte : md5Bytes) {
            int val = ((int) md5Byte) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }

            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }


}
